<template>
  <px-dialog v-model="dialogVisible" class="equip-dialog-wrap" :title="data ? '编辑' : '新增'" width="50%" align-center>
    <px-form ref="formRef" :model="queryParams" label-position="right" label-width="110px">
      <px-form-item prop="tableName" label="值班日历名称" :rules="[{ required: true, message: '值班日历名称不能为空', trigger: 'blur' }]">
        <px-input
          v-model="queryParams.tableName"
          placeholder="请输入"
          clearable
          maxlength="50"
          @blur="queryParams.tableName = $event.target.value.trim()"
        />
      </px-form-item>
      <px-form-item prop="tableStatus" label="是否启用" :rules="[{ required: true, message: '是否启用不能为空', trigger: 'blur' }]">
        <px-radio-group v-model="queryParams.tableStatus">
          <px-radio label="OFF">不启用</px-radio>
          <px-radio label="ON">启用</px-radio>
        </px-radio-group>
      </px-form-item>
      <px-form-item
        v-if="dialogVisible"
        v-loading="loading"
        prop="attachment"
        label="附件"
        :rules="[{ required: true, validator: validateAttach, trigger: 'blur' }]"
      >
        <FileUpload
          v-show="(type === 'edit' && !loading) || type === 'add'"
          :countLimit="1"
          fileType="add"
          accept=".xlsx, xls"
          :fileData="{ moduleName: '' }"
          :fileLists="fileLists"
          :fileSize="100"
          @change-file-list="changeFileList"
          @saveFileStatus="saveFileStatus"
        />
      </px-form-item>
      <px-form-item class="align-right">
        <px-button @click="handleCancel">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
      </px-form-item>
    </px-form>
  </px-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import FileUpload from "./FileUpload.vue";
import { PxMessage } from "px-ui";
import type { FormInstance } from "px-ui";
import { getToken } from "@/utils/auth";
import { dutycreate, dutyUpdate, dutyEnumQuery } from "@/api/erc/duty";
import axios from "axios";
const props = defineProps(["data", "type"]);
const dialogVisible = defineModel("dialogVisible");
const formRef = ref();
const fileLists = ref([]);
const fileStatus = ref<boolean>(false);
const emits = defineEmits(["refresh"]);
const tableStatusOptions = ref();
const loading = ref<boolean>(false);
const validateAttach = (rule, value, callback) => {
  if (fileLists.value.length <= 0) {
    callback(new Error("附件不能为空"));
  }
  callback();
};
onMounted(() => {
  dutyEnumQuery().then(res => {
    tableStatusOptions.value = res;
  });
});
const queryParams = ref<{
  tableName?: string;
  tableStatus: string;
  attachment?: string;
}>({
  tableName: "",
  tableStatus: "OFF",
  attachment: ""
});
watch(dialogVisible, () => {
  if (!dialogVisible.value) {
    formRef.value.resetFields();
    fileLists.value = [];
    queryParams.value = { tableStatus: "OFF" };
  }
});
watch(
  () => [props.data, dialogVisible],
  () => {
    if (props.data && dialogVisible.value) {
      queryParams.value = { ...props.data, factoryAreaCode: props.data.facCode };
      fileLists.value = [];
      getData();
    } else {
      fileLists.value = [];
      queryParams.value = { tableStatus: "OFF" };
    }
  }
);
const getData = () => {
  loading.value = true;
  axios({
    method: "post",
    url: "/ifp/sharing/api/v1/file/get",
    headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + getToken().accessToken || "",
      facCode: localStorage.getItem("facCode") || ""
    },
    data: {
      id: props.data.attachment
    }
  })
    .then(res => {
      if (res?.data?.success) {
        fileLists.value = [res.data?.data];
        formRef?.value?.clearValidate("attachment");
      } else {
        PxMessage.error(res.data.msg);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
const changeFileList = val => {
  fileLists.value = val;
  formRef?.value?.clearValidate("attachment");
};
const saveFileStatus = (flag: boolean) => {
  fileStatus.value = flag;
};
const handleSubmit = async (formEl: InstanceType<typeof FormInstance> | undefined) => {
  if (fileStatus.value) {
    return PxMessage.error("文件正在上传中，请稍后再试");
  }
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = {
        id: props.data?.id,
        tableName: queryParams.value.tableName,
        tableStatus: queryParams.value.tableStatus,
        attachment: fileLists.value[0]?.id
      };
      // await acceptTask(data);
      if (props.type === "add") {
        await dutycreate(data);
        PxMessage.success("提交成功");
      } else {
        await dutyUpdate(data);
        PxMessage.success("编辑成功");
      }
      emits("refresh");
      dialogVisible.value = false;
    }
  });
};
const handleCancel = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
@import url("../../scss/add-dialog.scss");

.align-right {
  :deep(.px-form-item__content) {
    justify-content: flex-end;
  }
}
</style>
